package com.business.business.web.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.business.business.common.base.BaseService;
import com.business.business.common.utils.appkit.ConfigKit;
import com.business.business.common.utils.cache.RedisUtil;
import com.business.business.model.*;
import com.business.business.model.construction_unit.ConstructionUnitAptitude;
import com.business.business.model.construction_unit.ConstructionUnitAptitudeAnnex;
import com.business.business.model.construction_unit.ConstructionUnitInfo;
import com.business.business.support.model.RespEntity;
import com.business.business.support.utils.requestutil.HttpRequestUtil;
import com.business.business.web.mapper.*;
import com.business.business.web.mapper.construction_unit.ConstructionUnitAptitudeAnnexMapper;
import com.business.business.web.mapper.construction_unit.ConstructionUnitAptitudeMapper;
import com.business.business.web.mapper.construction_unit.ConstructionUnitInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Yang
 */
@Service
@Slf4j
public class BusinessService extends BaseService {
    private static final Logger logger = LoggerFactory.getLogger(BusinessService.class);
    @Resource
    private FireDepartmentMapper fireDepartmentMapper;
    @Resource
    private IndustryAuthoritiesMapper industryAuthoritiesMapper;
    @Resource
    private BusinessMapper businessMapper;
    @Resource
    private RegionMapper regionMapper;
    @Resource
    RedisUtil redisUtil;
    @Resource
    private BusinessCustomizeManagePersonMapper businessCustomizeManagePersonMapper;
    @Resource
    private BusinessTypeMapper businessTypeMapper;
    @Resource
    private IndustryMapper industryMapper;
    @Resource
    private UseDictMapper useDictMapper;
    @Resource
    private DictMapper dictMapper;
    @Resource
    private ShouldKnowMapper shouldKnowMapper;
    @Resource
    private BusinessFirefightingplanMapper businessFirefightingplanMapper;
    @Resource
    private BusinessFirepreventionplanMapper businessFirepreventionplanMapper;
    @Resource
    private BusinessRulesandregulationsMapper businessRulesandregulationsMapper;
    @Resource
    private BusinessFiretrainingMapper businessFiretrainingMapper;
    @Resource
    private BusinessLegaldocumentsMapper businessLegaldocumentsMapper;
    @Resource
    private BusinessCheckaddrMapper businessCheckaddrMapper;
    @Resource
    private BusinessInspectionPlanMapper businessInspectionPlanMapper;
    @Resource
    private BusinessCheckmanagePersonMapper businessCheckmanagePersonMapper;
    @Resource
    private PictureMapper pictureMapper;
    @Resource
    private RenewaRecordMapper renewaRecordMapper;
    @Resource
    private PressureGaugeValueDefaultMapper pressureGaugeValueDefaultMapper;
    @Resource
    private PressureGaugeValueMapper pressureGaugeValueMapper;
    @Resource
    private BusinessTypeNewMapper businessTypeNewMapper;
    @Resource
    private OrganizationMapper organizationMapper;
    @Resource
    private ConstructionUnitInfoMapper constructionUnitInfoMapper;
    @Resource
    private ConstructionUnitAptitudeAnnexMapper constructionUnitAptitudeAnnexMapper;
    @Resource
    private ConstructionUnitAptitudeMapper constructionUnitAptitudeMapper;
    @Resource
    private BusinessEvaluationService businessEvaluationService;
    /**
     * 消防主管部门树形列表
     *
     * @param jsonParam
     * @return
     */
    public RespEntity fireDepartmentTreeList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String id = "010107";
        FireDepartment fireDepartment = fireDepartmentMapper.selectById(id);
        List<FireDepartment> orgs = getfireDepartmentTreeList(id);
        fireDepartment.put("orgs", orgs);
        return RespEntity.success(fireDepartment);
    }

    public List<FireDepartment> getfireDepartmentTreeList(String id) {
        List<FireDepartment> list = new ArrayList<>();
        List<FireDepartment> oneList = fireDepartmentMapper.selectList(new QueryWrapper<FireDepartment>().eq("pid", id));
        for (FireDepartment one : oneList) {
            List<FireDepartment> twoList = getfireDepartmentTreeList(one.getId());
            one.put("orgs", twoList);
            list.add(one);
        }
        return list;
    }

    /**
     * 相符部门树形列表
     *
     * @param jsonParam
     * @return
     */
    public RespEntity industryAuthoritiesTreeList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String id = "01010D";
        IndustryAuthorities fireDepartment = industryAuthoritiesMapper.selectById(id);
        List<IndustryAuthorities> orgs = getindustryAuthoritiesTreeList(id);
        fireDepartment.put("orgs", orgs);
        return RespEntity.success(fireDepartment);
    }

    public List<IndustryAuthorities> getindustryAuthoritiesTreeList(String id) {
        List<IndustryAuthorities> list = new ArrayList<>();
        List<IndustryAuthorities> oneList = industryAuthoritiesMapper.selectList(new QueryWrapper<IndustryAuthorities>().eq("pid", id));
        for (IndustryAuthorities one : oneList) {
            List<IndustryAuthorities> twoList = getindustryAuthoritiesTreeList(one.getId());
            one.put("orgs", twoList);
            list.add(one);
        }
        return list;
    }

    /**
     * 单位不分页列表数目
     *
     * @param jsonParam
     * @return
     */
    public RespEntity businessListCount(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if (userType.equals("1")) {//为机构用户
            //rest请求系统设置模块的机构和子机构列表接口
            if (StrUtil.isBlank(jsonParam.getStr("orgId"))) {
                jsonParam.put("orgId", homeId);
            }
            JSON jsons = makeDataForJSONForToken(jsonParam, "systemsetup", "config", "orgAllList", "systemsetup");
            if (jsons instanceof com.alibaba.fastjson.JSONObject) {
                com.alibaba.fastjson.JSONObject weekAlarmObjectN = (com.alibaba.fastjson.JSONObject) jsons;
                if (StrUtil.isNotBlank(weekAlarmObjectN.getString("methodCodeFlag"))) {
                    return RespEntity.expire();
                }
                return RespEntity.fail(((com.alibaba.fastjson.JSONObject) jsons).getString("msg"));
            } else {
                JSONArray orgIdList = (JSONArray) jsons;
                if (orgIdList != null && !orgIdList.isEmpty()) {
                    jsonParam.put("orgIdList", orgIdList);
                    jsonParam.put("orgIdListFlag", "1");
                }
            }
        }
        int count = businessMapper.getBuCount(jsonParam);
        Map<String, Object> map = new HashMap<>();
        map.put("count", count);
        return RespEntity.success(map);
    }

    /**
     * 行政区划树形菜单
     *
     * @param jsonParam
     * @return
     */
    public RespEntity regionTreeList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        logger.info("regionTreeList---------------"+jsonParam.toString());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String reginid = token.getString("reginid");
        logger.info("regionTreeList-----------token----homeId:"+homeId+"-----userId:"+userId+"-------userType:"+userType+"-------reginid:"+reginid);
        if (redisUtil.get("reginid"+reginid) != null) {
            //redisUtil.remove("regionTreeList");
            return RespEntity.success(redisUtil.get("reginid"+reginid));
        }
        //一级
        List<Region> oneList = regionMapper.selectList(new QueryWrapper<Region>().eq("id", reginid));
        for (Region one : oneList) {
            //二级
            List<Region> twoList = regionMapper.selectList(new QueryWrapper<Region>().eq("pid", one.getId()));
            for (Region two : twoList) {
                //三级
                List<Region> threeList = regionMapper.selectList(new QueryWrapper<Region>().eq("pid", two.getId()));
                for (Region three : threeList) {
                    //四级
                    List<Region> fourList = regionMapper.selectList(new QueryWrapper<Region>().eq("pid", three.getId()));
                    for (Region four : fourList) {
                        //五级
                        List<Region> fiveList = regionMapper.selectList(new QueryWrapper<Region>().eq("pid", four.getId()));
                        for (Region five : fourList) {
                            //六级
                            List<Region> sixList = regionMapper.selectList(new QueryWrapper<Region>().eq("pid", five.getId()));
                            five.put("regions", sixList);
                        }
                        four.put("regions", fiveList);
                    }
                    three.put("regions", fourList);
                }
                two.put("regions", threeList);
            }
            one.put("regions", twoList);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("regions", oneList);
        redisUtil.set("reginid"+reginid, map);
        //文件读取的方式开始-----------------------------------------
//        String path = "D://全国.json";
//        System.out.println(path);
//        String s = readJsonFile(path);
//        com.alibaba.fastjson.JSONObject jobj = JSON.parseObject(s);
//        JSONArray movies = jobj.getJSONArray("regions");//构建JSONArray数组
//        map.put("regions", movies);
        //文件读取的方式结束----------------------------------------
        return RespEntity.success(map);
    }

    /**
     * @Author YangYu
     * @Description 行政区划新增
     * @Date Created in 13:53 2022/5/7
     * @Param [jsonParam]
     */

    public RespEntity regionAdd(JSONObject jsonParam){
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String reginid = token.getString("reginid");

        String name = jsonParam.getStr("name");
        String pid = jsonParam.getStr("pid");
        String id = UUID.randomUUID().toString();
        Region region = regionMapper.selectById(pid);
        String pname = region.getName();
        String allname = region.getAllname()+","+name;
        String allid = region.getAllid()+","+id;
        String level = region.getLevel()+1;

        region = new Region();
        region.setId(id);
        region.setName(name);
        region.setPid(pid);
        region.setPname(pname);
        region.setLevel(level);
        region.setAllname(allname);
        region.setAllid(allid);
        regionMapper.insert(region);
        //清除缓存数据
        redisUtil.remove("reginid"+reginid);
        return RespEntity.success(region);
    }

    /**
     * @Author YangYu
     * @Description 行政区划删除
     * @Date Created in 14:11 2022/5/7
     * @Param [jsonParam]
     */

    public RespEntity regionDel(JSONObject jsonParam){
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String reginid = token.getString("reginid");
        if (StrUtil.isBlank(jsonParam.getStr("id")) || jsonParam.getStr("id").equals("")){
            return RespEntity.fail("ID不能为空!");
        }else {
            int count = regionMapper.selectCount(new QueryWrapper<Region>().eq("pid",jsonParam.getStr("id")));
            if (count > 0){
                return RespEntity.fail("存在下级行政区划不能删除!");
            }else {
                regionMapper.deleteById(jsonParam.getStr("id"));
                //清除缓存数据
                redisUtil.remove("reginid"+reginid);
            }

        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 行政区划更新
     * @Date Created in 14:11 2022/5/7
     * @Param [jsonParam]
     */

    public RespEntity regionUpdate(JSONObject jsonParam){
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String reginid = token.getString("reginid");
        if (StrUtil.isBlank(jsonParam.getStr("id")) || jsonParam.getStr("id").equals("")){
            return RespEntity.fail("ID不能为空!");
        }else {
            Region region1 = regionMapper.selectById(jsonParam.getStr("id"));
            Region region2 = regionMapper.selectById(region1.getPid());
            Region region = new Region();
            region.setId(jsonParam.getStr("id"));
            region.setName(jsonParam.getStr("name"));
            region.setAllname(region2.getAllname()+","+jsonParam.getStr("name"));
            regionMapper.updateById(region);
            //清除缓存数据
            redisUtil.remove("reginid"+reginid);
        }
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 行政区划详情
     * @Date Created in 14:11 2022/5/7
     * @Param [jsonParam]
     */

    public RespEntity regionDetail(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String reginid = token.getString("reginid");
        if (jsonParam ==null || StrUtil.isBlank(jsonParam.getStr("id")) || jsonParam.getStr("id").equals("")){
            return RespEntity.fail("ID不能为空!");
        }
        Region region = regionMapper.selectById(jsonParam.getStr("id"));
        return RespEntity.success(region);
    }
    /**
     * 查询行政区划id
     * @param jsonParam
     * @return
     */
    public RespEntity getGegionList(JSONObject jsonParam) {
        List<Region> regionList = regionMapper.getGegionList();
        return RespEntity.success(regionList);
    }

    /**
     * 查询单位导出数据
     * @param jsonParam
     * @return
     */
    public RespEntity getBusiness(JSONObject jsonParam) {
        List<Business> regionList = businessMapper.getBusiness();
        return RespEntity.success(regionList);
    }

    /**
     * 单位详情
     * @param jsonParam
     * @return
     */
    public RespEntity getBusinessDetail(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if(userType.equals("1")){

        }else if(userType.equals("2")){
            jsonParam.put("id",homeId);
        }
        //查询单位
        Business business = businessMapper.getBusinessList(jsonParam).get(0);

        //判断单位是否存在
        if (business==null){
            return RespEntity.fail("单位已删除或单位不存在!");
        }
        if(business.getHighRisk().equals("1")){
            business.put("isHighRisk",true);
        }else{
            business.put("isHighRisk",false);
        }
        //查询自定义管理人员
        List<BusinessCustomizeManagePerson> list = businessCustomizeManagePersonMapper.selectList(new QueryWrapper<BusinessCustomizeManagePerson>().eq("business_id",jsonParam.getStr("id")));
        //判断是否存在自定义管理员
        if (!list.isEmpty()){
            business.put("businessCustomizeManagePersonList",list);
        }
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("id",business.getOrgId());
        com.alibaba.fastjson.JSONObject jsonObject = makeData(jsonObject1, "systemsetup", "config", "orgDetail", "systemsetup");
        String orgName = jsonObject.getString("name");
        business.put("orgName", orgName);
        business.setScore(businessEvaluationService.getBusinessEvaluation(business));
        businessMapper.updateById(business);
        return RespEntity.success(business);
    }

    /**
     * 单位详情(不带token)
     * @param jsonParam
     * @return
     */
    public RespEntity getBusinessDetailNoToken(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //查询单位
        Business business = businessMapper.getBusinessList(jsonParam).get(0);
        //判断单位是否存在
        if (business==null){
            return RespEntity.fail("单位已删除或单位不存在!");
        }
        //查询自定义管理人员
        List<BusinessCustomizeManagePerson> list = businessCustomizeManagePersonMapper.selectList
                (new QueryWrapper<BusinessCustomizeManagePerson>().eq("business_id",jsonParam.getStr("id")));
        //判断是否存在自定义管理员
        if (!list.isEmpty()){
            business.put("businessCustomizeManagePersonList",list);
        }
        return RespEntity.success(business);
    }
    /**
     * 查询所有的单位Id
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getBusinessId(JSONObject jsonParam) {
//        //处理支持form-data和json两种方式
//        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
//        //调用token验证接口
//        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
//        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
//        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
//        String homeId = token.getString("home_id");
//        String userId = token.getString("user_id");
//        String userType = token.getString("user_type");
        //获取所有单位的id
        List<Business> businessIdList = businessMapper.getBusinessId();
        List<String> businessList = new ArrayList<>();
        for (Business business : businessIdList) {
            businessList.add(business.getId());
        }
        return RespEntity.success(businessList);
    }

    /**
     * 单位新增服务
     *
     * @param jsonObject
     * @return
     */
    public RespEntity businessAdd(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = "";
        if(StrUtil.isNotBlank(jsonObject.getStr("orgId"))){
            homeId = jsonObject.getStr("orgId");
        }else{
            if (token.getString("user_type").equals("2")){
                homeId = "001e7548-8735-4b31-b30b-c9361a62c102";
            }else {
                homeId = token.getString("home_id");
            }
        }
        jsonObject.put("homeId",homeId);
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String area = jsonObject.getStr("area");
        String name = jsonObject.getStr("name");
        String lon = jsonObject.getStr("lon");
        String lat = jsonObject.getStr("lat");
        String addr = jsonObject.getStr("addr");
        String fireRating = jsonObject.getStr("fireRating");
        String unitProperty = jsonObject.getStr("unitProperty");
        String enterpriseCode = jsonObject.getStr("enterpriseCode");
        String isHighRisk = jsonObject.getStr("isHighRisk");
        String oneResponPersonName = jsonObject.getStr("oneResponPersonName");
        String oneResponPersonPhone = jsonObject.getStr("oneResponPersonPhone");
        String safeResponPersonName = jsonObject.getStr("safeResponPersonName");
        String safeResponPersonPhone = jsonObject.getStr("safeResponPersonPhone");
        String safeManagePersonName = jsonObject.getStr("safeManagePersonName");
        String safeManagePersonPhone = jsonObject.getStr("safeManagePersonPhone");
        String industry = jsonObject.getStr("industry");
        String unitCategory = jsonObject.getStr("unitCategory");
        String persons = jsonObject.getStr("persons");
        String industryAuthoritiesId = jsonObject.getStr("industryAuthoritiesId");
        String fireDepartmentId = jsonObject.getStr("fireDepartmentId");
        //根据area查询region表
        Map map = selectRegion(area);
        String allname = map.get("allname").toString();
        String allid = map.get("allid").toString();
        //生成主键id
        String id = UUID.randomUUID().toString();
        //获得当前时间
        DateTime createtime = DateUtil.date();
        Calendar calendar = new GregorianCalendar();
        Date expiretime = createtime;
        calendar.setTime(expiretime);
        calendar.add(Calendar.YEAR, 1);//把日期往后增加一年.整数往后推,负数往前移动
        expiretime=calendar.getTime();
        //封装数据
        Business business = new Business();
        business.setExpiretime(expiretime);
        business.setId(id);
        jsonObject.put("id",id);
        business.setOrgId(homeId);
        jsonObject.put("DJorgId",business.getOrgId());
        business.setName(name);
        business.setLon(lon);
        business.setLat(lat);
        business.setAddr(addr);
        business.setFireRating(fireRating);
        business.setUnitProperty(unitProperty);
        business.setEnterpriseCode(enterpriseCode);
        business.setHighRisk(isHighRisk);
        business.setArea(allid);
        business.setAreaName(allname);
        business.setOneResponPersonName(oneResponPersonName);
        business.setOneResponPersonPhone(oneResponPersonPhone);
        business.setSafeResponPersonName(safeResponPersonName);
        business.setSafeResponPersonPhone(safeResponPersonPhone);
        business.setSafeManagePersonName(safeManagePersonName);
        business.setSafeManagePersonPhone(safeManagePersonPhone);
        business.setIndustry(industry);
        business.setUnitCategory(unitCategory);
        business.setDel(false);
        business.setCreatetime(createtime);
        Organization organization = organizationMapper.selectById(homeId);
        business.setOrgIds(organization.getAllId());
        business.setFireDepartmentId(fireDepartmentId);
        business.setIndustryAuthoritiesId(industryAuthoritiesId);
        business.setUsableArea(jsonObject.getDouble("usableArea"));
        business.setNumberLayers(jsonObject.getInt("numberLayers"));
        business.setNumberPeople(jsonObject.getInt("numberPeople"));
        //保存数据库表business中
        int businessInsert = this.businessMapper.insert(business);
        //查询对应的字典表
        UseDict fireRatingDict = useDictMapper.selectById(jsonObject.getStr("fireRating"));
        //解析persons
        if (!persons.equals("[]")) {
            JSONArray data = com.alibaba.fastjson.JSONObject.parseArray(persons);
            int businessCustomizeManagePersonInsert = 0;
            for (Object obj : data){
                com.alibaba.fastjson.JSONObject json = (com.alibaba.fastjson.JSONObject)obj;
                Set<String> keys = json.keySet();
                String typeName = null;
                for (String k : keys) {
                    typeName = k;
                }
                JSONArray jsonArray = json.getJSONArray(typeName);
                String personName = jsonArray.get(0).toString();
                String personPhone = jsonArray.get(1).toString();
                BusinessCustomizeManagePerson businessCustomizeManagePerson = new BusinessCustomizeManagePerson();
                businessCustomizeManagePerson.setBusinessId(id);
                businessCustomizeManagePerson.setPersonName(personName);
                businessCustomizeManagePerson.setPersonPhone(personPhone);
                businessCustomizeManagePerson.setTypeName(typeName);
                businessCustomizeManagePersonInsert = businessCustomizeManagePersonMapper.insert(businessCustomizeManagePerson);
            }
        }
        return RespEntity.success(id);
    }

    /**
     * 批量插入单位
     * @param jsonParm
     * @return
     */
    public RespEntity businessAllAdd(JSONObject jsonParm) {

        List<Business> businessList = (List<Business>)jsonParm.get("busineslist");
        businessMapper.insertZB(businessList);
        return RespEntity.success();
    }

    /**
     * 消防支队新增单位
     * @param jsonObject
     * @return
     */
    public RespEntity fireFightingBusinessAdd(JSONObject jsonObject) {
        logger.info("消防单位新增开始:"+jsonObject);
        //rest调用消防支队
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("MC", jsonObject.getStr("name"));
        UseDict unitPropertyDict = useDictMapper.selectById(jsonObject.getStr("unitProperty"));
        String KindBH = "";
        if ("机关".equals(unitPropertyDict.getName())) {
            KindBH = "01";
        }
        if ("团体".equals(unitPropertyDict.getName())) {
            KindBH = "02";
        }
        if ("企业".equals(unitPropertyDict.getName())) {
            KindBH = "03";
        }
        if ("事业".equals(unitPropertyDict.getName())) {
            KindBH = "04";
        }
        if ("其它".equals(unitPropertyDict.getName())) {
            KindBH = "05";
        }
        jsonParam.put("KindBH", KindBH);
        jsonParam.put("KindMC", unitPropertyDict.getName());
        UseDict fireRatingDict = useDictMapper.selectById(jsonObject.getStr("fireRating"));
        String TypeBH = "";
        if ("消防安全重点单位".equals(fireRatingDict.getName())) {
            TypeBH = "01";
        }
        if ("消防安全一般单位".equals(fireRatingDict.getName())) {
            TypeBH = "02";
        }
        if ("九小场所".equals(fireRatingDict.getName())) {
            TypeBH = "03";
        }
        jsonParam.put("TypeBH", TypeBH);
        jsonParam.put("TypeMC", fireRatingDict.getName());
        BusinessType businessType = businessTypeMapper.selectById(jsonObject.getStr("unitCategory"));
        jsonParam.put("LbBH", businessType.getId());
        jsonParam.put("LbMC", businessType.getName());
        Industry industrys = industryMapper.selectById(jsonObject.getStr("industry"));
        jsonParam.put("IndustryDictBH", industrys.getId());
        jsonParam.put("IndustryDictMC", industrys.getName());
        List<Region> oneList = regionMapper.selectList(new QueryWrapper<Region>().eq("id", jsonObject.getStr("area")));
        Region region = oneList.get(0);
        jsonParam.put("AreaBH", region.getId());
        String AreaMC = region.getAllname().replace(",", "-");
        jsonParam.put("AreaMC", AreaMC);
        jsonParam.put("Address", jsonObject.getStr("addr"));
        IndustryAuthorities industryAuthorities = industryAuthoritiesMapper.selectById(jsonObject.getStr("industryAuthoritiesId"));
        jsonParam.put("IndustryBH", industryAuthorities.getId());
        jsonParam.put("IndustryMC", industryAuthorities.getName());
        FireDepartment fireDepartment = fireDepartmentMapper.selectById(jsonObject.getStr("fireDepartmentId"));
        jsonParam.put("FireDeptBH", fireDepartment.getId());
        jsonParam.put("FireDeptMC", fireDepartment.getName());
        jsonParam.put("FireManager", jsonObject.getStr("safeResponPersonName"));
        jsonParam.put("FireManagerTel", jsonObject.getStr("safeManagePersonPhone"));
        jsonParam.put("FireDuty", jsonObject.getStr("safeManagePersonName"));
        jsonParam.put("FireDutyTel", jsonObject.getStr("safeManagePersonPhone"));
        jsonParam.put("MLng", jsonObject.getStr("lon"));
        jsonParam.put("MLat", jsonObject.getStr("lat"));
        logger.info("消防单位新增结束:"+jsonParam);
        logger.info("消防单位新增结束jsonObject:"+jsonObject);
        String fireFlag = ConfigKit.getStr("fireFlag","config");
        if(fireFlag.equals("1")){
            //查询消防支队是否存在此单位
            cn.hutool.json.JSONArray CompanyInfo = fireFightingiotJSONArray(jsonParam, "Intelligentfire2", "zhyGetCompanyInfo", "jointFire",jsonObject.getStr("name"));
            //消防支队单位id
            String ComID = "";
            if (!CompanyInfo.isEmpty()){
                JSONObject comid = (JSONObject)CompanyInfo.get(0);
                ComID = comid.getStr("ComID");
            }else {
                com.alibaba.fastjson.JSONObject ComId = new com.alibaba.fastjson.JSONObject();
                if ("e349f82a-c7a7-4e67-a1ff-ae0aca8940f3".equals(jsonObject.getStr("homeId"))){
                    ComId = fireFightingiotTwo(jsonParam, "Intelligentfire2", "sbrsCompanyInfo", "jointFire");
                }else {
                    ComId = fireFightingiotTwo(jsonParam, "Intelligentfire2", "zhyCompanyInfo", "jointFire");
                }
                if (!ComId.containsKey("Data")) {
                    return RespEntity.fail("请求消防失败!");
                }
                com.alibaba.fastjson.JSONObject comId = ComId.getJSONObject("Data");
                ComID = comId.getString("ComID");
            }
            Business business = new Business();
            business.setId(jsonObject.getStr("id"));
            business.setFireId(ComID);
            businessMapper.updateById(business);
        }
        return RespEntity.success();
    }
    //根据area查询region表
    public Map selectRegion(String area) {
        List<Region> regionList = regionMapper.selectList(new QueryWrapper<Region>().eq("id", area));
        Region region = regionList.get(0);
        String allname = (String) region.get("allname");
        String allid = (String) region.get("allid");
        Map regionMap = new HashMap();
        regionMap.put("allid", allid);
        regionMap.put("allname", allname);
        return regionMap;
    }

    @Resource
    BusinessHandleService businessHandleService;
    /**
     * 单位更新服务
     *
     * @param jsonParam
     * @return
     */
    public RespEntity businessUpdate(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String area = jsonParam.getStr("area");
        String name = jsonParam.getStr("name");
        String enterpriseCode = jsonParam.getStr("enterpriseCode");
        String isHighRisk = jsonParam.getStr("isHighRisk");
        String lon = jsonParam.getStr("lon");
        String lat = jsonParam.getStr("lat");
        String addr = jsonParam.getStr("addr");
        String fireRating = jsonParam.getStr("fireRating");
        String unitProperty = jsonParam.getStr("unitProperty");
        String oneResponPersonName = jsonParam.getStr("oneResponPersonName");
        String oneResponPersonPhone = jsonParam.getStr("oneResponPersonPhone");
        String safeResponPersonName = jsonParam.getStr("safeResponPersonName");
        String safeResponPersonPhone = jsonParam.getStr("safeResponPersonPhone");
        String safeManagePersonName = jsonParam.getStr("safeManagePersonName");
        String safeManagePersonPhone = jsonParam.getStr("safeManagePersonPhone");
        String industry = jsonParam.getStr("industry");
        String unitCategory = jsonParam.getStr("unitCategory");
        String id = jsonParam.getStr("id");
        String isDel = jsonParam.getStr("isDel");
        String persons = jsonParam.getStr("persons");
        String industryAuthoritiesId = jsonParam.getStr("industryAuthoritiesId");
        String fireDepartmentId = jsonParam.getStr("fireDepartmentId");
        Business businessName = businessMapper.selectById(id);
        if (!businessName.getName().equals(name)){
            fireFightingiot(jsonParam, "firefightingiot", "updateBusinessName", "device");
        }
        String[] areas = area.split(",");
        //根据area查询region表
        Map map = selectRegion(areas[areas.length-1]);
        String allname = map.get("allname").toString();
        String allid = map.get("allid").toString();
        //实例化实体类
        Business business = new Business();
        //封装实体类填充数据
        business.setArea(area);
        business.setName(name);
        business.setEnterpriseCode(enterpriseCode);
        business.setHighRisk(isHighRisk);
        business.setLon(lon);
        business.setLat(lat);
        business.setAddr(addr);
        business.setFireRating(fireRating);
        business.setUnitProperty(unitProperty);
        business.setOneResponPersonName(oneResponPersonName);
        business.setOneResponPersonPhone(oneResponPersonPhone);
        business.setSafeResponPersonName(safeResponPersonName);
        business.setSafeResponPersonPhone(safeResponPersonPhone);
        business.setSafeManagePersonName(safeManagePersonName);
        business.setSafeManagePersonPhone(safeManagePersonPhone);
        business.setIndustry(industry);
        business.setArea(allid);
        business.setAreaName(allname);
        business.setUnitCategory(unitCategory);
        business.setId(id);
        business.setDel(Boolean.parseBoolean(isDel));
        business.setFireDepartmentId(fireDepartmentId);
        business.setIndustryAuthoritiesId(industryAuthoritiesId);
        business.setUsableArea(jsonParam.getDouble("usableArea"));
        business.setNumberLayers(jsonParam.getInt("numberLayers"));
        business.setNumberPeople(jsonParam.getInt("numberPeople"));
        //查询原来orgId
        String orgIdOld = businessName.getOrgId();
        //前端传过来的新orgId
        String orgIdNew = jsonParam.getStr("orgId");
        jsonParam.put("DJorgId",orgIdNew);
        if (orgIdNew!=null && StrUtil.isNotBlank(orgIdNew) && !orgIdNew.equals(orgIdOld)) {
            //查询allIds
            jsonParam.put("homeId",orgIdNew);
            com.alibaba.fastjson.JSONObject allIds = makeDataForToken(jsonParam, "systemsetup", "config", "orgAllLists", "systemsetup");
            business.setOrgId(orgIdNew);
            business.setOrgIds(allIds.getString("orgIds"));
            //异步处理相关表的修改
            businessHandleService.updateOrgId(jsonParam,allIds.getString("orgIds"));
        }else{
            jsonParam.put("homeId",homeId);
        }
        //更新输入
        int updateById = this.businessMapper.updateById(business);
        //根据id删除
        int deleteById = this.businessCustomizeManagePersonMapper.delete(new QueryWrapper<BusinessCustomizeManagePerson>().eq("business_id",id));
        //解析persons
        if (!persons.equals("[]")) {
            JSONArray data = com.alibaba.fastjson.JSONObject.parseArray(persons);
            int businessCustomizeManagePersonInsert = 0;
            for (Object obj : data){
                com.alibaba.fastjson.JSONObject json = (com.alibaba.fastjson.JSONObject)obj;
                Set<String> keys = json.keySet();
                String typeName = null;
                for (String k : keys) {
                    typeName = k;
                }
                JSONArray jsonArray = json.getJSONArray(typeName);
                String personName = jsonArray.get(0).toString();
                String personPhone = jsonArray.get(1).toString();
                BusinessCustomizeManagePerson businessCustomizeManagePerson = new BusinessCustomizeManagePerson();
                businessCustomizeManagePerson.setBusinessId(id);
                businessCustomizeManagePerson.setPersonName(personName);
                businessCustomizeManagePerson.setPersonPhone(personPhone);
                businessCustomizeManagePerson.setTypeName(typeName);
                businessCustomizeManagePersonInsert = businessCustomizeManagePersonMapper.insert(businessCustomizeManagePerson);
            }
            /*if (updateById > 0 && deleteById > 0 && businessCustomizeManagePersonInsert > 0) {
                return RespEntity.success();
            }*/
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 更新CameraType
     * @Date Created in 10:43 2021/3/25
     * @Param [jsonParam]
     */

    public RespEntity updateCameraType(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        Business business = new Business();
        business.setId(jsonParam.getStr("businessId"));
        business.setCameraType(jsonParam.getStr("cameraType"));
        businessMapper.updateById(business);
        return RespEntity.success();
    }
    /**
     * 查询所有的单位Id
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getBusinessList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        //获取所有单位
        List<Business> businessList = businessMapper.getBusinessList(jsonParam);
        return RespEntity.success(businessList.toString());
    }

    /**
     * 根据行政区划查询单位
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getBusinessLists(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        //获取所有单位
        List<Business> businessList = businessMapper.selectList(new QueryWrapper<Business>().like("area",jsonParam.getStr("regionId")).like("org_ids",homeId).eq("is_del",0));
        return RespEntity.success(businessList);
    }
    /**
     * 删除redis里边的key
     *
     * @param jsonParam
     * @return
     */
    public RespEntity removeKey(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        redisUtil.remove(jsonParam.getStr("key"));
        return RespEntity.success();
    }
    /**
     * 1.查询所有的单位列表id,name,ord_id
     * 2.查询所有的下级机构id
     * 3.所包含的单位列表放到新的list中,再放到redis中
     */
    /**
     * 查询单位list
     *
     * @param jsonParam
     * @return
     */
    public RespEntity businessList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (jsonParam.containsKey("orgId") && StrUtil.isNotBlank(jsonParam.getStr("orgId"))) {
            jsonParam.put("homeId", jsonParam.getStr("orgId"));
        } else {
            jsonParam.put("homeId", homeId);
        }
//        if(redisUtil.get("businessList")!=null){
//            //redisUtil.remove("regionTreeList");
//
//        }
        List<Business> businessList = businessMapper.BusinessList(jsonParam);
//        redisUtil.set("businessList",businessList);
        return RespEntity.success(businessList);
    }

    /**
     * 更新区划方法
     * @param jsonParam
     * @return
     */
    public RespEntity region(JSONObject jsonParam) {
        List<Region> regionList = regionMapper.getAllId();
        String str = "";
        for (Region org :regionList ){
            String name = "";
            str = org.getAllid();
            String strs[] = str.split(",");
            for (int i = 0; i <strs.length ; i++) {
                Region region = regionMapper.selectById(strs[i]);
                name += region.getName() + ",";
            }
            Region regions = new Region();
            regions.setId(org.getId());
            regions.setAllname(name.substring(0,name.length()-1));
            regionMapper.updateById(regions);
        }
        return RespEntity.success();
    }

    /**
     * 单位删除
     * @param jsonParam
     * @return
     */
    public RespEntity businessDelete(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        //查询单位下是否存在设备
        int deviceConunt =  restCount(jsonParam,"firefightingiot","getDeviceCount","device","GET");
        if (deviceConunt>0){
            return RespEntity.fail("本单位下存在设备无法删除!");
        }
        //查询单位下是否存在启用账号
        int businessNumber =  restEvaluation(jsonParam,"systemsetup","userCount","systemsetup");
        if (businessNumber>0) {
            return RespEntity.fail("本单位下存在启用账号无法删除!");
        }
        Business business = businessMapper.selectById(jsonParam.getStr("businessId"));
        jsonParam.put("homeId",business.getId());
        jsonParam.put("pid",business.getOrgId());
        makeDataForToken(jsonParam, "communicationJava", "config", "releaseNumberPieces", "communication");
        //删除单位下的所有数据
        business.setDel(true);
        businessMapper.updateById(business);
        //businessMapper.deleteById(jsonParam.getStr("businessId"));
        return RespEntity.success();
    }

    /**
     * @Author LiHaoDong
     * @Description 单位列表
     * @Date 16:06 2020/7/20
     * @Param [jsonParam]
     * @return com.business.business.support.model.RespEntity
     **/
    public RespEntity businessListPage(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        logger.info("businessListPage----------------"+jsonParam.toString());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        Page<Business> page = new Page<>(jsonParam.getInt("page"),jsonParam.getInt("limit"));
        jsonParam.put("homeId",homeId);
        if(jsonParam.containsKey("area") && jsonParam.get("area")!=null && jsonParam.getStr("area").equals("0")){
            jsonParam.put("area","");
        }
        jsonParam.put("type",jsonParam.getBool("type")+"");
        if (!jsonParam.containsKey("sort")){
            jsonParam.put("sort","no");
        }
        IPage<Business> iPage =  businessMapper.selectBusinessListPage(page, jsonParam);
        List<Business> records = iPage.getRecords();
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", iPage.getTotal());
        data.put("pages", iPage.getPages());
        data.put("pageSize", jsonParam.getInt("limit"));
        data.put("Items",records);
        data.put("currentPage",jsonParam.getInt("page"));
        data.put("currentSize",jsonParam.getInt("limit"));
        return RespEntity.success(data);
    }

    /**
     * 字典组查询
     * @param jsonParam
     * @return
     */
    public RespEntity dictList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        List<Dict>  dictList = dictMapper.selectList(new QueryWrapper<Dict>().eq("groupname",jsonParam.getStr("groupname")));
        return RespEntity.success(dictList);
    }

    /**
     * 行业列表
     * @param jsonParam
     * @return
     */
    public RespEntity industryList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        List<Industry> industry = industryMapper.selectList(new QueryWrapper<Industry>().eq("level",1));
        for (Industry str : industry){
            List<Industry> industryList =   industryMapper.selectList(new QueryWrapper<Industry>().eq("pid",str.getId()));
            str.put("industrys",industryList);
        }
        return RespEntity.success(industry);
    }

    //应知应会列表
    public List shouldknowList(String id) {
        return getindustryAuthoritiesTree("0");
    }

    public List<ShouldKnow> getindustryAuthoritiesTree(String id) {
        List<ShouldKnow> list = new ArrayList<>();
        List<ShouldKnow> oneList = shouldKnowMapper.selectList(new QueryWrapper<ShouldKnow>().eq("pid", id));
        for (ShouldKnow one : oneList) {
            List<ShouldKnow> twoList = getindustryAuthoritiesTree(one.getId());
            one.put("childs", twoList);
            list.add(one);
        }
        return list;
    }

    //根据消防等级分类统计机构单位数目
    public RespEntity businessCount(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        List<Dict> dicts = this.dictMapper.selectList(new QueryWrapper<Dict>().eq("groupname", "消防等级"));

        String orgId = jsonParam.getStr("orgId");

        HashMap<String, Object> date = new HashMap<>();

        for (Dict dict : dicts) {
            if (dict.getName().equals("消防安全重点单位")) {
               date.put("important",this.businessMapper.selectCount(new QueryWrapper<Business>().eq("fire_rating", dict.getId())));
            } else if (dict.getName().equals("消防安全一般单位")) {
                date.put("commonly",this.businessMapper.selectCount(new QueryWrapper<Business>().eq("fire_rating", dict.getId())));
            } else if (dict.getName().equals("九小场所")) {
                date.put("nineSmall",this.businessMapper.selectCount(new QueryWrapper<Business>().eq("fire_rating", dict.getId())));
            } else if (dict.getName().equals("其它")) {
                date.put("other",this.businessMapper.selectCount(new QueryWrapper<Business>().eq("fire_rating", dict.getId())));
            }
        }
        if (!date.isEmpty()) {
            return RespEntity.success(date);
        }
        return RespEntity.fail();
    }

    /**
     * @Author YangYu
     * @Description 单位接入统计(根据单位类型统计)
     * @Date Created in 11:20 2022/5/24
     * @Param [jsonParam]
     */

    public RespEntity businessCounts(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        HashMap<String, Object> date = new HashMap<>();
        int count = businessMapper.selectCount(new QueryWrapper<Business>().like("org_ids",homeId).eq("business_type",jsonParam.getStr("businessType")));
        date.put("businessCounts",count);
        return RespEntity.success(date);
    }
    /**
     * 单位类别
     */
    public RespEntity businessTypeList(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        if (jsonParam.containsKey("fireRatingId") && StrUtil.isNotBlank(jsonParam.getStr("fireRatingId"))){
            if (jsonParam.getStr("fireRatingId").equals("001e7548-8735-4b31-b30b-c9361a62c903")){
                jsonParam.put("fireRatingId","001e7548-8735-4b31-b30b-c9361a62c902");
            }
            List<BusinessTypeNew> list = businessTypeNewMapper.selectList(new QueryWrapper<BusinessTypeNew>().eq("pid",jsonParam.getStr("fireRatingId")));
            return RespEntity.success(list);
        }else {
            List<BusinessType> list = businessTypeListTree("");
            return RespEntity.success(list);
        }
    }
    public List<BusinessType> businessTypeListTree(String id) {
        List<BusinessType> list = new ArrayList<>();
        List<BusinessType> oneList = businessTypeMapper.selectList(new QueryWrapper<BusinessType>().eq("pid", id));
        for (BusinessType one : oneList) {
            List<BusinessType> twoList = businessTypeListTree(one.getId());
            one.put("businessTypes", twoList);
            list.add(one);
        }
        return list;
    }

    /**
     * 获取所有上级行政区划接口
     */
    public RespEntity getAllArea(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        String bottomArea = jsonParam.getStr("bottomArea");
        Region region = this.regionMapper.selectOne(new QueryWrapper<Region>().eq("id", bottomArea));
        if (!region.isEmpty()) {
            HashMap hashMap = new HashMap();
            hashMap.put("allArea",region.getAllid());
            return RespEntity.success(hashMap);
        }
        return RespEntity.fail();
    }

    /**
     * 详情页面数据统计
     */


    public RespEntity statistics(JSONObject jsonParam){

        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        String businessId = jsonParam.getStr("id");
        if (businessId == null) {
            businessId = homeId;
        }
        //Integer businessFirefightingplan = this.businessFirefightingplanMapper.selectCount(new QueryWrapper<BusinessFirefightingplan>().eq("business_id", businessId));
        Integer businessFirefightingplan = this.businessFirefightingplanMapper.firefightingPlanCount(businessId);

        Integer businessFirepreventionplan = this.businessFirepreventionplanMapper.selectCount(new QueryWrapper<BusinessFirepreventionplan>().eq("business_id", businessId));

        Integer businessRulesandregulations = this.businessRulesandregulationsMapper.selectCount(new QueryWrapper<BusinessRulesandregulations>().eq("business_id", businessId));

        Integer businessFiretraining = this.businessFiretrainingMapper.selectCounts(businessId);

        Integer businessLegaldocuments = this.businessLegaldocumentsMapper.selectCount(new QueryWrapper<BusinessLegaldocuments>().eq("business_id", businessId));

        Integer businessPicture = this.pictureMapper.selectCount(new QueryWrapper<Picture>().eq("business_id", businessId));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("businessId",businessId);
        Integer getCheckaddrCount = restEvaluation(jsonObject, "check", "getCheckaddrCount", "check");
        Integer getInspectionPlanCount = restEvaluation(jsonObject, "check", "getInspectionPlanCount", "check");


        /*Integer businessCheckaddr = this.businessCheckaddrMapper.selectCount(new QueryWrapper<BusinessCheckaddr>().eq("business_id", businessId));
        Integer businessInspectionPlan = this.businessInspectionPlanMapper.selectCount(new QueryWrapper<BusinessInspectionPlan>().eq("business_id", businessId));
*/
        HashMap hashMap = new HashMap();
        hashMap.put("firefightingplanNum", businessFirefightingplan);
        hashMap.put("firepreventionplanNum", businessFirepreventionplan);
        hashMap.put("rulesandregulationsNum", businessRulesandregulations);
        hashMap.put("firetrainingNum", businessFiretraining);
        hashMap.put("legaldocumentsNum", businessLegaldocuments);
        hashMap.put("checkaddrNum", getCheckaddrCount);
        hashMap.put("planNum", getInspectionPlanCount);
        hashMap.put("pictureNum", businessPicture);

        if (!hashMap.isEmpty()) {
            return RespEntity.success(hashMap);
        }
        return RespEntity.fail();
    }

    /**
     * 续费
     */
    public RespEntity renew(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String time = jsonParam.getStr("time");//type
        long number = jsonParam.getLong("number");
        String id = jsonParam.getStr("id");
        String name = jsonParam.getStr("name");
        Business business = this.businessMapper.selectById(id);
        String expiretime = business.getStr("expiretime");
        if (time.equals("天")) {
            try {
                Date newDate = plusDay(expiretime, number);
                business.setExpiretime(newDate);
                this.businessMapper.updateById(business);
                renewaRecordAdd(jsonParam);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else if (time.equals("月")) {
            number = number * 30;
            try {
                Date newDate = plusDay(expiretime, number);
                business.setExpiretime(newDate);
                this.businessMapper.updateById(business);
                renewaRecordAdd(jsonParam);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else if (time.equals("年")) {
            number = number * 365;
            try {
                Date newDate = plusDay(expiretime, number);
                business.setExpiretime(newDate);
                this.businessMapper.updateById(business);
                renewaRecordAdd(jsonParam);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        //更新账号状态
        businessMapper.updateUser(id);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 查看单位服务是否到期
     * @Date Created in 14:08 2022/6/30
     * @Param [jsonParam]
     */

    public RespEntity checkBusinessExpire(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        return RespEntity.success(businessMapper.checkBusinessExpire(homeId));
    }
    /**
     * 支付成功回调
     *
     * @param
     * @return
     */
    public Map<String, String> onCallback() throws IOException {


        Map<String, Object> map = HttpRequestUtil.commonHttpRequestParamConvert2(getRequest());
        // TODO 打印回调参数  逻辑代码没写
        Set<String> set = map.keySet();
        for(String str : set){
            System.out.println("回调参数:----------"+str+"--------"+map.get(str));
        }
        System.out.println("----------------stop------------------");
        Map<String, String> wxPayMap = new HashMap<>();
        wxPayMap.put("code", "SUCCESS");
        wxPayMap.put("message", "成功");
        return wxPayMap;
    }

    //操作续费记录
    public void renewaRecordAdd(JSONObject jsonParam){
        RenewaRecord renewaRecord = new RenewaRecord();
        renewaRecord.setId(UUID.randomUUID().toString());
        DateTime createtime = DateUtil.date();
        renewaRecord.setTime(createtime);
        renewaRecord.setType(jsonParam.getStr("time"));//type
        renewaRecord.setNumber(jsonParam.getStr("number"));
        renewaRecord.setBusinessId(jsonParam.getStr("id"));
        renewaRecord.setBusinessName(jsonParam.getStr("name"));
        this.renewaRecordMapper.insert(renewaRecord);
    }
    /**
     * 指定日期加上天数后的日期
     * @throws ParseException
     */
    public static Date plusDay(String time,long day ) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); // 日期格式
        Date date = dateFormat.parse(time); // 指定日期
        Date newDate = addDate(date, day); // 指定日期加上20天
        return newDate;
    }

    public static Date addDate(Date date,long day) {
        long time = date.getTime(); // 得到指定日期的毫秒数
        day = day*24*60*60*1000; // 要加上的天数转换成毫秒数
        time+=day; // 相加得到新的毫秒数
        return new Date(time); // 将毫秒数转换成日期
    }


    /**
     * 获取监管人员列表
     */
    public RespEntity getCheckmanagePersonList(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        List<BusinessCheckmanagePerson> list = businessCheckmanagePersonMapper.selectList(new QueryWrapper<BusinessCheckmanagePerson>());
        return RespEntity.success(list);
    }

    /**
     * 行政区划列表
     *
     * @param jsonParam
     * @return
     */
    public RespEntity regionList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String reginid = token.getString("reginid");
        List<Region> regionList = regionMapper.selectList(new QueryWrapper<Region>().eq("pid",jsonParam.getStr("pid")));
        return RespEntity.success(regionList);
    }
    /**
     * 测试网络
     */
    public RespEntity checkNet(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());

        try{
            com.alibaba.fastjson.JSONObject jSONObject = fireFightingiotTwo(jsonParam,"firefightingiot","checkNet","iotCheckNet");
            if(!(jSONObject!=null && jSONObject.get("code")!=null && jSONObject.getInteger("code") == 0)){

            }
        }catch(Exception e){

        }
        fireFightingiotTwo(jsonParam,"dataaccess","checkNet","dataCheckNet");
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 欠费的企业更新账号状态为2
     * @Date Created in 15:08 2022/6/21
     */

    public void updateUser(){
        //查询到期的单位
        List<Map<String,Object>> businessList = businessMapper.getBusinessLists();
        //更新到期单位账号的是否在用状态
        businessMapper.batchUpdate(businessList);
    }

    /**
     * @Author YangYu
     * @Description  设置仪表盘数据
     * @Date Created in 16:11 2023/2/28
     * @Param [jsonParam]
     */

    public RespEntity setPressureGaugeValue(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        if (StrUtil.isBlank(jsonParam.getStr("businessId"))){
            return RespEntity.fail("businessId不能为空!");
        }
        pressureGaugeValueMapper.delete(new QueryWrapper<PressureGaugeValue>().eq("business_id",jsonParam.getStr("businessId")));
        PressureGaugeValue pressureGaugeValue = new PressureGaugeValue();
        pressureGaugeValue.setBusinessId(jsonParam.getStr("businessId"));
        pressureGaugeValue.setMaximum(jsonParam.getDouble("maximum"));
        pressureGaugeValue.setMinimum(jsonParam.getDouble("minimum"));
        pressureGaugeValueMapper.insert(pressureGaugeValue);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description  获取仪表盘数据
     * @Date Created in 16:11 2023/2/28
     * @Param [jsonParam]
     */

    public RespEntity getPressureGaugeValue(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        if (StrUtil.isBlank(jsonParam.getStr("businessId"))){
            return RespEntity.fail("businessId不能为空!");
        }
        PressureGaugeValue pressureGaugeValue = pressureGaugeValueMapper.selectOne(new QueryWrapper<PressureGaugeValue>().eq("business_id",jsonParam.getStr("businessId")));
        if (pressureGaugeValue == null){
            PressureGaugeValueDefault pressureGaugeValueDefault = pressureGaugeValueDefaultMapper.selectOne(new QueryWrapper<>());
            pressureGaugeValue = new PressureGaugeValue();
            pressureGaugeValue.setMaximum(pressureGaugeValueDefault.getMaximum());
            pressureGaugeValue.setMinimum(pressureGaugeValueDefault.getMinimum());
        }
        return RespEntity.success(pressureGaugeValue);
    }

    /**
     * @Author YangYu
     * @Description  更新企业NFC_ID
     * @Date Created in 16:11 2023/2/28
     * @Param [jsonParam]
     */

    public RespEntity updateBusinessNfcID(JSONObject jsonParam){
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        if (StrUtil.isBlank(jsonParam.getStr("id"))){
            return RespEntity.fail("id不能为空!");
        }
        Business businessOld = businessMapper.selectById(jsonParam.getStr("id"));
        if (StrUtil.isNotBlank(businessOld.getNfcId()) && !businessOld.getNfcId().equals(jsonParam.getStr("nfcId"))){
            int count = businessMapper.selectCount(new QueryWrapper<Business>().eq("nfc_id",jsonParam.getStr("nfcId")));
            if (count > 0){
                return RespEntity.fail("NFC已绑定,请更换NFC标签再进行绑定!");
            }
        }else if (StrUtil.isBlank(businessOld.getNfcId())){
            int count = businessMapper.selectCount(new QueryWrapper<Business>().eq("nfc_id",jsonParam.getStr("nfcId")));
            if (count > 0){
                return RespEntity.fail("NFC已绑定,请更换NFC标签再进行绑定!");
            }
        }
        Business business = new Business();
        business.setId(jsonParam.getStr("id"));
        business.setNfcId(jsonParam.getStr("nfcId"));
        businessMapper.updateById(business);
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 单位统计(根据单位类别)
     * @Date Created in 17:11 2024/4/27
     * @Param [jsonParam]
     */

    public RespEntity getBusinessTypeCountList(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        QueryWrapper<Business> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("COUNT(unit_category) as `count`","(select name from business_type_new where business_type_new.id = business.unit_category) as unitCategoryName")
                .like("org_ids",homeId)
                .groupBy("unit_category")
                .orderByDesc("count");
        List<Business> businessList = businessMapper.selectList(queryWrapper);
        return RespEntity.success(businessList);
    }


    /**
     * @Author YangYu
     * @Description 施工单位新增、编辑
     * @Date Created in 10:26 2024/7/11
     * @Param [jsonParam]
     */

    public RespEntity constructionUnitAddOrUpdate(JSONObject jsonParam){
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        ConstructionUnitInfo constructionUnitInfo = new ConstructionUnitInfo();
        //校验新增还是修改
        if (jsonParam.containsKey("id") && StrUtil.isNotBlank(jsonParam.getStr("id"))){
            constructionUnitInfo.setId(jsonParam.getStr("id"));
            //删除旧数据
            constructionUnitInfoMapper.deleteById(jsonParam.getStr("id"));
        }else {
            constructionUnitInfo.setId(UUID.randomUUID().toString());
        }
        constructionUnitInfo.setName(jsonParam.getStr("name"));
        constructionUnitInfo.setEnterpriseCode(jsonParam.getStr("enterpriseCode"));
        constructionUnitInfo.setAddr(jsonParam.getStr("addr"));
        constructionUnitInfo.setResponPersonName(jsonParam.getStr("responPersonName"));
        constructionUnitInfo.setResponPersonPhone(jsonParam.getStr("responPersonPhone"));
        constructionUnitInfo.setLegalPerson(jsonParam.getStr("legalPerson"));
        constructionUnitInfo.setRegisteredCapital(jsonParam.getStr("registeredCapital"));
        constructionUnitInfo.setEstablishDate(jsonParam.getStr("establishDate"));
        constructionUnitInfo.setOperatingPeriod(jsonParam.getStr("operatingPeriod"));
        constructionUnitInfo.setBusinessScope(jsonParam.getStr("businessScope"));
        constructionUnitInfo.setApprovalTime(jsonParam.getStr("approvalTime"));
        constructionUnitInfo.setCreateTime(DateUtil.now());
        constructionUnitInfoMapper.insert(constructionUnitInfo);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 施工单位详情
     * @Date Created in 10:26 2024/7/11
     * @Param [jsonParam]
     */

    public RespEntity constructionUnitDetails(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        //校验新增还是修改
        if (jsonParam.containsKey("id") && StrUtil.isNotBlank(jsonParam.getStr("id"))){
            ConstructionUnitInfo constructionUnitInfo = constructionUnitInfoMapper.selectById(jsonParam.getStr("id"));
            return RespEntity.success(constructionUnitInfo);
        }
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 施工单位分页列表
     * @Date Created in 10:26 2024/7/11
     * @Param [jsonParam]
     */

    public RespEntity constructionUnitListPage(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        Page<ConstructionUnitInfo> page = new Page<>(jsonParam.getInt("page"),jsonParam.getInt("limit"));
        IPage<ConstructionUnitInfo> iPage =  constructionUnitInfoMapper.constructionUnitListPage(page, jsonParam);
        List<ConstructionUnitInfo> records = iPage.getRecords();
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", iPage.getTotal());
        data.put("pages", iPage.getPages());
        data.put("pageSize", jsonParam.getInt("limit"));
        data.put("Items",records);
        data.put("currentPage",jsonParam.getInt("page"));
        data.put("currentSize",jsonParam.getInt("limit"));
        return RespEntity.success(data);
    }


    /**
     * @Author YangYu
     * @Description 施工单位资质新增、编辑
     * @Date Created in 10:26 2024/7/11
     * @Param [jsonParam]
     */

    public RespEntity aptitudeAddOrUpdate(JSONObject jsonParam){
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        ConstructionUnitAptitude constructionUnitAptitude = new ConstructionUnitAptitude();
        //校验新增还是修改
        if (jsonParam.containsKey("id") && StrUtil.isNotBlank(jsonParam.getStr("id"))){
            constructionUnitAptitude.setId(jsonParam.getStr("id"));
            //删除旧数据
            constructionUnitAptitudeMapper.deleteById(jsonParam.getStr("id"));
        }else {
            constructionUnitAptitude.setId(UUID.randomUUID().toString());
        }
        constructionUnitAptitude.setConstructionUnitId(jsonParam.getStr("constructionUnitId"));
        constructionUnitAptitude.setAptitudeType(jsonParam.getInt("aptitudeType"));
        constructionUnitAptitude.setNumber(jsonParam.getStr("number"));
        constructionUnitAptitude.setIssuanceDate(jsonParam.getStr("issuanceDate"));
        constructionUnitAptitude.setValidTo(jsonParam.getStr("validTo"));
        constructionUnitAptitude.setLicenceIssuingAuthority(jsonParam.getStr("licenceIssuingAuthority"));
        constructionUnitAptitude.setCreateTime(DateUtil.now());
        constructionUnitAptitudeMapper.insert(constructionUnitAptitude);
        //添加资质名称
        if (jsonParam.containsKey("aptitudeName") && StrUtil.isNotBlank(jsonParam.getStr("aptitudeName"))) {
            String[] aptitudeNames = jsonParam.getStr("aptitudeName").split(",");
            for (String aptitudeName : aptitudeNames) {
                ConstructionUnitAptitudeAnnex constructionUnitAptitudeAnnex = new ConstructionUnitAptitudeAnnex();
                constructionUnitAptitudeAnnex.setAptitudeId(constructionUnitAptitude.getId());
                constructionUnitAptitudeAnnex.setAnnexInfo(aptitudeName);
                constructionUnitAptitudeAnnex.setConstructionUnitId(constructionUnitAptitude.getConstructionUnitId());
                constructionUnitAptitudeAnnex.setType(1);
                constructionUnitAptitudeAnnexMapper.insert(constructionUnitAptitudeAnnex);
            }
        }
        //添加资质证书
        if (jsonParam.containsKey("aptitudeCertificateImg") && StrUtil.isNotBlank(jsonParam.getStr("aptitudeCertificateImg"))) {
            String[] aptitudeCertificateImgs = jsonParam.getStr("aptitudeCertificateImg").split(",");
            for (String aptitudeCertificateImg : aptitudeCertificateImgs) {
                ConstructionUnitAptitudeAnnex constructionUnitAptitudeAnnex = new ConstructionUnitAptitudeAnnex();
                constructionUnitAptitudeAnnex.setAptitudeId(constructionUnitAptitude.getId());
                constructionUnitAptitudeAnnex.setAnnexInfo(aptitudeCertificateImg);
                constructionUnitAptitudeAnnex.setConstructionUnitId(constructionUnitAptitude.getConstructionUnitId());
                constructionUnitAptitudeAnnex.setType(2);
                constructionUnitAptitudeAnnexMapper.insert(constructionUnitAptitudeAnnex);
            }
        }
        //添加人员资质证书
        if (jsonParam.containsKey("personnelAptitudeCertificateImg") && StrUtil.isNotBlank(jsonParam.getStr("personnelAptitudeCertificateImg"))) {
            String[] personnelAptitudeCertificateImgs = jsonParam.getStr("personnelAptitudeCertificateImg").split(",");
            for (String personnelAptitudeCertificateImg : personnelAptitudeCertificateImgs) {
                ConstructionUnitAptitudeAnnex constructionUnitAptitudeAnnex = new ConstructionUnitAptitudeAnnex();
                constructionUnitAptitudeAnnex.setAptitudeId(constructionUnitAptitude.getId());
                constructionUnitAptitudeAnnex.setAnnexInfo(personnelAptitudeCertificateImg);
                constructionUnitAptitudeAnnex.setConstructionUnitId(constructionUnitAptitude.getConstructionUnitId());
                constructionUnitAptitudeAnnex.setType(3);
                constructionUnitAptitudeAnnexMapper.insert(constructionUnitAptitudeAnnex);
            }
        }
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 资质详情
     * @Date Created in 17:01 2024/7/11
     * @Param [jsonParam]
     */

    public RespEntity aptitudeDetails(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        ConstructionUnitAptitude constructionUnitAptitude = constructionUnitAptitudeMapper.selectOne(new QueryWrapper<ConstructionUnitAptitude>().eq("construction_unit_id",jsonParam.getStr("constructionUnitId")).eq("aptitude_type",jsonParam.getInt("aptitudeType")));
        //名称
        List<ConstructionUnitAptitudeAnnex> aptitudeNameList = constructionUnitAptitudeAnnexMapper.selectList(new QueryWrapper<ConstructionUnitAptitudeAnnex>().eq("aptitude_id",constructionUnitAptitude.getId()).eq("type",1));
        constructionUnitAptitude.set("aptitudeNameList",aptitudeNameList);
        //资质证书
        List<ConstructionUnitAptitudeAnnex> aptitudeCertificateImgList = constructionUnitAptitudeAnnexMapper.selectList(new QueryWrapper<ConstructionUnitAptitudeAnnex>().eq("aptitude_id",constructionUnitAptitude.getId()).eq("type",2));
        constructionUnitAptitude.set("aptitudeCertificateImgList",aptitudeCertificateImgList);
        //人员资质证书
        List<ConstructionUnitAptitudeAnnex> personnelAptitudeCertificateImgList = constructionUnitAptitudeAnnexMapper.selectList(new QueryWrapper<ConstructionUnitAptitudeAnnex>().eq("aptitude_id",constructionUnitAptitude.getId()).eq("type",3));
        constructionUnitAptitude.set("personnelAptitudeCertificateImgList",personnelAptitudeCertificateImgList);
        return RespEntity.success(constructionUnitAptitude);
    }
}
